<template>
  <div class="main">
    <el-form ref="queryRef" :model="queryParams" :inline="true">
      <el-form-item style="margin-left: 20px" label="等级" prop="level">
        <el-select
          v-model="queryParams.level"
          style="width: 200px"
          placeholder="请选择等级"
        >
          <el-option
            v-for="item in levelOptions"
            :key="item.id"
            :label="item.level"
            :value="item.level"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="床位" prop="beds">
        <el-input-number
          v-model="queryParams.beds"
          :min="1"
          :max="9"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery(queryRef)">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button
          v-perms="['hotel:roomtypes:add']"
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-perms="['hotel:roomtypes:edit']"
          type="success"
          plain
          icon="Edit"
          :disabled="!single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-perms="['hotel:roomtypes:delete']"
          type="danger"
          plain
          icon="Delete"
          :disabled="!multiple"
          @click="deleteBatch"
          >批量删除</el-button
        >
      </el-col>
    </el-row>
    <br />
    <el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        style="font-size: 17px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="编号" align="center" width="80" />
        <el-table-column prop="image" label="图片" align="center">
          <template #default="scope">
            <img :src="scope.row.image" alt="图片" class="table-image" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="房型名称" align="center" />
        <el-table-column prop="type" label="类型" align="center" width="80" />
        <el-table-column prop="level" label="等级" align="center" width="80" />
        <el-table-column prop="beds" label="床位" align="center" width="80" />
        <el-table-column
          prop="basicPrice"
          label="价格(元)"
          align="center"
          width="100"
        />
        <el-table-column
          prop="deposit"
          label="押金(元)"
          align="center"
          width="100"
        />
        <el-table-column
          v-perms="['hotel:roomtypes:edit']"
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              v-perms="['hotel:roomtypes:edit']"
              link
              type="primary"
              icon="Edit"
              size="large"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              v-perms="['hotel:roomtypes:delete']"
              link
              type="primary"
              icon="Delete"
              size="large"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- 数据展示区：分页加载 -->
    <el-pagination
      v-model:page-size="queryParams.pageSize"
      v-model:current-page="queryParams.pageNum"
      style="margin-top: 20px"
      :page-sizes="[5, 10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="dialogOpen" :title="title" width="500">
      <!-- 前面是子组件,后面是本地 -->
      <RoomTypesForm
        :action="action"
        :roomTypesId="roomTypesId"
        :ruleform="ruleform"
        :dialogOpen="dialogOpen"
        @close="handleCloseDialog"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
let a = ref(111);
import { provide, reactive, ref, toRef } from "vue";
import { onMounted } from "vue";
import RoomTypesForm from "@/views/hotel/roomtypes/form.vue";
import {
  listAllRoomTypes,
  deleteRoomTypesBatch,
  getRoomTypeById,
  listRoomTypesByPage,
  getRoomTypeslevels
} from "@/api/roomtypes";
import type {
  RoomtypesParams,
  RoomtypesDTO,
  RoomtypesForm
} from "@/api/roomtypes";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";

// 页面加载时，得到列表数据
onMounted(() => {
  getList();
});
/** ------------------数据查询区——表单------------------ */
// 表单实例
const queryRef = ref<FormInstance>();

const total = ref<number>(0); // table数据总数
const loading = ref<boolean>(false); // table数据加载遮罩
const tableData = reactive<RoomtypesDTO[]>([]); // table数据
const dataList = toRef(tableData);

// 类别下拉框
const categoryOptions = ref<RoomtypesParams[]>([]);
const levelOptions = ref([]);
function getlevels() {
  getRoomTypeslevels().then(response => {
    levelOptions.value = response.data;
  });
}
// 查询
const query = reactive<RoomtypesParams>({
  pageNum: 1,
  pageSize: 5,
  level: undefined,
  beds: undefined,
  name: undefined,
  type: undefined
});
const queryParams = toRef(query);
// 数据查询区--> 查询按钮
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
// 数据查询区--> 重置按钮
const resetQuery = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getList();
};
/** ------------------数据展示区：数据表格-------------------- */

// 去掉静态数据
const categoryList = ref<RoomtypesParams[]>([]);
/** 得到列表数据 */
function getList() {
  loading.value = true;
  getlevels();
  listRoomTypesByPage(queryParams.value)
    .then(response => {
      dataList.value = response.data.records;
      total.value = response.data.total;
      loading.value = false;
    })
    .catch(() => {
      console.log(queryParams.value);
    });
}

/** ------------------数据展示区：数据选择-------------------- */

const ids = ref<number[]>([]); // 表单勾选的id
const single = ref<boolean>(false); // 勾选1个
const multiple = ref<boolean>(false); // 勾选多个
// 数据展示区--> 勾选数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length == 1;
  multiple.value = selection.length >= 1;
}

/** ------------------数据操作-------------------- */
const dialogOpen = ref<boolean>(false); //对话框打开
const title = ref<string>("");
const roomTypesId = ref<number>();
const action = ref<string>();
const formRef = ref<FormInstance>();
const formData = reactive<RoomtypesForm>({
  type: undefined,
  beds: undefined,
  name: undefined,
  basicPrice: undefined,
  level: undefined,
  id: undefined,
  deposit: undefined
});
const ruleform = toRef(formData);
const initForm = () => {
  formRef.value?.resetFields();
  ruleform.value = { ...formData };
};

/** 新增按钮 */
function handleAdd() {
  action.value = "add";
  initForm();
  roomTypesId.value = undefined;
  title.value = "新增类别";
  dialogOpen.value = true;
}

/** 修改按钮 */
async function handleUpdate(row: any) {
  dialogOpen.value = false;
  initForm();
  roomTypesId.value = row.id || ids.value[0];
  await getRoomTypeById(roomTypesId.value).then(response => {
    ruleform.value = response.data;
    console.log(response.data);
    console.log("图片?");
  });
  console.log("shifou");
  action.value = "update";
  title.value = "修改数据[" + roomTypesId.value + "]";
  dialogOpen.value = true;
}

/** 删除按钮 */
function handleDelete(row: any) {
  const id = row.id;
  ElMessageBox.confirm("是否删除编号为" + id + "的数据?", "警告")
    .then(() => {
      return deleteRoomTypesBatch(id).then(response => {
        ElMessage({ type: "success", message: response.msg });
      });
    })
    .then(() => {
      getList();
    })
    .catch(() => {});
}
/** 批量删除按钮 */
function deleteBatch() {
  const roomTypesIds = ids.value;
  ElMessageBox.confirm("是否删除编号为" + roomTypesIds + "的数据?", "警告")
    .then(() => {
      return deleteRoomTypesBatch(roomTypesIds).then(response => {
        ElMessage({ type: "success", message: response.msg });
      });
    })
    .then(() => {
      getList();
    })
    .catch(() => {});
}

/** 关闭对话框 */
function handleCloseDialog() {
  dialogOpen.value = false;
  roomTypesId.value = undefined;
  action.value = undefined;
  getList();
}
//------------------------------------------
// 分页--> 修改每页数据数（5｜10｜20｜30）
function handleSizeChange(val: number) {
  queryParams.value.pageSize = val;
  getList();
}

//分页--> 修改当前页
function handleCurrentChange(val: number) {
  queryParams.value.pageNum = val;
  getList();
}
</script>
